package com.alipay.sofa.award.endpoint.exception;

import java.text.MessageFormat;

/**
 * CommonException
 * <p/>
 * Created by yangguanchao on 16/11/18.
 */
public class CommonException extends Exception{

    /***
     * Error Code
     */
    private ErrorCodeDescFacade errorCodeDescFacade;

    /**
     * 参数数组
     */
    private Object[]            messageParams = null;

    public CommonException(ErrorCodeDescFacade errorCodeDescFacade) {
        this.errorCodeDescFacade = errorCodeDescFacade;
    }

    public CommonException(ErrorCodeDescFacade errorCodeDescFacade, Object... messages) {
        this.errorCodeDescFacade = errorCodeDescFacade;
        this.messageParams = messages;

    }

    public CommonException(ErrorCodeDescFacade errorCodeDescFacade, Throwable cause) {
        super(cause);
        this.errorCodeDescFacade = errorCodeDescFacade;
    }

    /**
     * 错误码英文描述并提供参数替换能力
     * @return 英文描述
     */
    public String getEnErrorDesc() {
        if (this.messageParams != null) {
            try {
                return MessageFormat.format(this.errorCodeDescFacade.getEnDesc(),
                        this.messageParams);
            } catch (Throwable throwable) {
                //异常情况:如配置错误,也可以返回相应的描述信息
                return this.errorCodeDescFacade.getEnDesc();
            }
        } else {
            return this.errorCodeDescFacade.getEnDesc();
        }
    }

    /**
     * 错误码中文描述并提供参数替换能力
     * @return 中文描述
     */
    public String getZhErrorDesc() {
        if (this.messageParams != null) {
            try {
                return MessageFormat.format(this.errorCodeDescFacade.getZhDesc(),
                        this.messageParams);
            } catch (Throwable throwable) {
                //异常情况:如配置错误,也可以返回相应的描述信息
                return this.errorCodeDescFacade.getZhDesc();
            }
        } else {
            return this.errorCodeDescFacade.getZhDesc();
        }
    }

    /**
     * 获取 ErrorCode
     *
     * @return ErrorCode
     */
    public String getErrorCode() {
        return this.errorCodeDescFacade.getCode();
    }
}
